import 'dart:convert';
import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base_library/index.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
// import 'package:safe_manage/config/my_app_data.dart';
import 'package:safe_manage/config/my_app_routes.dart';
import 'package:safe_manage/models/index.dart';
import 'package:safe_manage/widgets/img_detail_page.dart';

class AlarmInfoController extends GetxController {
  List<String> titleList = [
    "抽烟",
    "电子围栏",
    "电话",
    "烟火",
    "装卸油",
    "加油站巡检",
    "车顶作业",
    "人员识别",
    "设备状态监测",
    "离岗检测",
  ];
  int type = 0;
  late CommonRecord commonRecord;
  late String sjlx;
  var event = Rxn<EventRecord>();
  var imgUrl = Rxn<String>();
  var imgList = <RecordPicture>[].obs;
  var patrolModel = Rxn<Patrol>();
  var imgStrList = <String>[].obs;
  var videoList = <String>[];
  @override
  void onInit() {
    super.onInit();
    Map p = Get.parameters;
    type = int.tryParse(p["type"]) ?? 0;
    sjlx = p['sjlx'];
    commonRecord = Get.arguments;
    String? tpdz = commonRecord.tpdz;
    if (tpdz != null) {
      imgUrl.value = AppData.instance.baseUrl! + tpdz;
    }
    String? spdz = commonRecord.spdz;
    if (spdz != null && spdz.isNotEmpty) {
      var l = json.decode(spdz);
      if (l is List) {
        for (var element in l) {
          String baseUrl = AppData.instance.baseUrl!;
          List subStrs = baseUrl.split(":");
          if (subStrs.length >= 2) {
            baseUrl = subStrs[0] + ":" + subStrs[1];
          }
          videoList.add(
            baseUrl + element,
          );
        }
      }
    }
    _updataFirstEvent();
    _getDataInfo();
  }

  void _updataFirstEvent() async {
    await _getEventRecord();
    // if (commonRecord.sfcl != null) {
    //   event.value!.sfcl = commonRecord.sfcl;
    // }
  }

  Future _getEventRecord() {
    // User user = MyAppData.instance.currentUser!;
    // UserInfo userInfo = MyAppData.instance.currentUserInfo!;
    return HttpUtils.post(
      '/safety-web/eventRecord/getEventRecord',
      body: {
        "parameter": {
          "sjlx": sjlx,
          "jlid": commonRecord.id,
        },
      },
      success: (result) {
        var data = result['data'];
        if (data is Map<String, dynamic>) {
          event.value = EventRecord.fromJson(data);
          // commonRecord.sfcl = event.value!.sfcl;
        }
        EasyLoading.dismiss();
      },
      fail: (errorMsg) {
        EasyLoading.dismiss();
      },
    );
  }

  void _getDataInfo() {
    switch (type) {
      case 0:
        return;
      case 1:
        return;
      case 2:
        return;
      case 3:
        return;
      case 6:
        return;
      case 4:
        _zhuangXieYouRecordInfo();
        return;
      case 5:
        _getPatrolRecordInfo();
        _getPatrolRecord();
        return;
      default:
    }
  }

  void _zhuangXieYouRecordInfo() {
    HttpUtils.post(
      "/safety-web/zhuangXieYouRecordInfo/page",
      body: {
        "parameter": {
          "jlid": commonRecord.id,
        },
      },
      success: (result) {
        var data = result['data'];
        if (data is Map) {
          var records = data['records'];
          if (records is List) {
            for (var element in records) {
              RecordPicture pic = RecordPicture.fromJson(element);
              imgList.add(pic);
              String url = AppData.instance.baseUrl! + (pic.tpdz ?? "");
              imgStrList.add(url);
            }
          }
        }
      },
    );
  }

  void _getPatrolRecordInfo() {
    HttpUtils.post(
      "/safety-web/patrolRecordInfo/page",
      body: {
        "parameter": {
          "jlid": commonRecord.id,
        },
      },
      success: (result) {
        var data = result['data'];
        if (data is Map) {
          var records = data['records'];
          if (records is List) {
            for (var element in records) {
              RecordPicture pic = RecordPicture.fromJson(element);
              imgList.add(pic);
              String url = AppData.instance.baseUrl! + (pic.tpdz ?? "");
              imgStrList.add(url);
            }
          }
        }
      },
    );
  }

  void _getPatrolRecord() {
    HttpUtils.post(
      "/safety-web/patrolRecord/getById",
      body: {
        "parameter": {
          "id": commonRecord.id,
        },
      },
      success: (result) {
        var data = result['data'];
        if (data is Map<String, dynamic>) {
          patrolModel.value = Patrol.fromJson(data);
        }
      },
    );
  }

  void showImgDetails(BuildContext context) {
    List<BrnBasicGroupConfig> allConfig = [
      BrnPhotoGroupConfig(
        configList: [
          BrnPhotoItemConfig(
            url: imgUrl.value!,
            showBottom: true,
            bottomContentHeight: 20,
            // name: commonRecord.rwmc ?? "",
            name: "巡检类型：${titleList[type]}",
            des: () {
              int? milliseSecond = commonRecord.cjsj?.toInt();
              if (milliseSecond != null) {
                DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(
                  milliseSecond * 1000,
                );
                return "创建时间：${toLocalDateTimeByDateTime(dateTime)}";
              }
            }(),
          ),
        ],
      ),
    ];
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (BuildContext context) {
          return ImgDetailPage(
            allConfig: allConfig,
            themeData: BrnGalleryDetailConfig.light(),
          );
        },
      ),
    );
  }

  void showImgsDetails(BuildContext context, int index) {
    List<BrnBasicGroupConfig> allConfig = [
      BrnPhotoGroupConfig(
        configList: List.generate(
          imgList.length,
          (index) {
            var pic = imgList[index];
            String url = AppData.instance.baseUrl! + (pic.tpdz ?? "");
            return BrnPhotoItemConfig(
              url: url,
              showBottom: true,
              bottomContentHeight: 20,
              // name: commonRecord.rwmc ?? "",
              name: "巡检类型：${pic.xjlx}",
              des: () {
                int? milliseSecond = pic.cjsj?.toInt();
                if (milliseSecond != null) {
                  DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(
                    milliseSecond * 1000,
                  );
                  return "创建时间：${toLocalDateTimeByDateTime(dateTime)}";
                }
              }(),
            );
          },
        ),
      ),
    ];
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (BuildContext context) {
          return ImgDetailPage(
            allConfig: allConfig,
            initIndexId: index,
            themeData: BrnGalleryDetailConfig.light(),
          );
        },
      ),
    );
  }

  void videoClicked(int index) {
    // Get.toNamed(
    //   MyAppRoutes.alarmVideo,
    //   arguments: {
    //     "voideList": videoList,
    //     "index": index,
    //   },
    // );
    Get.toNamed(
      MyAppRoutes.fullVideo,
      arguments: videoList[index],
    );
  }

  void morePictureClicked(BuildContext context) {
    Get.toNamed(
      MyAppRoutes.alarmPictureList,
      // ignore: invalid_use_of_protected_member
      arguments: imgList.value,
      parameters: {
        "title": titleList[type],
        "bumen": commonRecord.cjbmmc ?? "",
      },
    );
  }

  void bottomButtonClicked() {
    Get.toNamed(
      MyAppRoutes.alarmHandle,
      arguments: {
        "record": commonRecord,
        "event": event.value,
        "sjlx": sjlx,
      },
    )?.then((value) {
      if (value != null && value is int) {
        EasyLoading.show();
        _getEventRecord();
      }
    });
  }
}
